package git.soulbgm.sync.task;

import git.soulbgm.sync.properties.DBSyncProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 同步数据库的任务
 *
 * @author SoulBGM
 * @date 2022/04/22 17:15
 */
public class SyncDataBaseTask {

    private final static Logger log = LoggerFactory.getLogger(SyncDataBaseTask.class);

    private final DBSyncProperties properties;

    private final RestTemplate template;

    public SyncDataBaseTask(DBSyncProperties properties, RestTemplate template) {
        this.properties = properties;
        this.template = template;
    }

    @Async
    public void sync(String sql) {
        List<String> syncIp = properties.getSyncIp();
        if (syncIp == null || syncIp.isEmpty()) {
            return;
        }
        for (String ipAndPort : syncIp) {
            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("sql", sql);
            HttpHeaders headers = new HttpHeaders();
            // 以表单的方式提交
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
            String result = template.postForObject(getUrl(ipAndPort), requestEntity, String.class);
            log.debug("{} 执行结果: {}, 同步SQL: {}", ipAndPort, result, sql);
        }
    }

    /**
     * 获取url
     *
     * @param ipAndPort IP和端口
     * @return 拼接之后的URL
     */
    public static String getUrl(String ipAndPort) {
        return "http://" + ipAndPort + "/executeSql";
    }

}
